const fs = require('fs')
const formatDate = require('../../utils/formatDate')

module.exports = async (ctx) => {
  const file = ctx.request.files.file

  const reader = fs.createReadStream(file.path)
  const ext = file.name.split('.').pop();		// 获取上传文件扩展名

  const crypto = require('crypto');
  const current_date = (new Date()).valueOf().toString()
  const hash = crypto.createHash('md5').update(current_date).digest('hex')

  const basePath = 'static/' + formatDate(new Date(), 'yyyy-MM')
  

  // 文件夹不存在侧创建文件夹
  if (!fs.existsSync(basePath)) fs.mkdirSync(basePath, 0777)

  const fileName = `${hash}.${ext}`
  const upStream = fs.createWriteStream(`${basePath}/${fileName}`)		// 创建可写流
  reader.pipe(upStream)	// 可读流通过管道写入可写流

  ctx.state.data = {
    url: `http://localhost:8585/${basePath}/${fileName}`,
    fileName: fileName
  }
}